<?php

require_once "../common/curl.php";

$string_name = "//div[@class='avatarholder']/a";
$id_file = 'region.txt';
$link_base = "http://www.erepublik.com";

$parties = array(2662=>"hkgolden",
								 2777=>"newsmth",
								 2726=>"saturn-community",
								 2654=>"soy-sauce-party",
								 2907=>"long-live-echina"
								);


function Parse($rid,$rname)
{
	global $string_name, $link_base, $parties;
	global $mycUrl;

	$result = '';
	
	echo "$rname\r\n";
	$result .= sprintf("%s\r\n", $rname);
	
	foreach ($parties as $pid => $pname) {
		
		$filename = "http://www.erepublik.com/en/propose-congressman/$pname-$pid/$rid";
	
		$file = $mycUrl->get($filename);
	
		$doc = new DOMDocument();
		$doc->loadHTML($file);
		$xpath = new DOMXpath($doc);	
	
		$elements = $xpath->query($string_name);
	
		foreach($elements as $element) {
			$link = $element->getAttribute('href');
			$name = $element->getAttribute('title');

			echo "$pname: $name\r\n";
			$result .= sprintf("\t%s: <a href='%s', target=_blank>%s</a>\r\n", $pname, $link_base.$link, $name);
		}
	
	}// foreach
	
	$result .= "--------------\r\n";
	
	return $result;
}


// main
$lines = file($id_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$content = '';
$mycUrl = new cUrl();

libxml_use_internal_errors(true);

foreach($lines as $line) {
	$a = explode(',', trim($line));
	$content .= Parse($a[0], $a[1]);
}

$content = "<html><body><pre>\r\n" . $content . "</pre></body></html>";

$file = fopen('candidate.html', 'w');
fwrite($file, $content);
fclose($file);

?>